今天我們用到了新的 PHP 方法
curl
可以輸入網址當成是一次網頁請求完成 POST 或 傳遞 GET 參數 的任務,甚至可以拿來當爬蟲取得資料
如果是取得該連結的頁面原始碼
<?php
$url = "輸入連結";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
echo $output; // 把網頁內容印出來
如果是打 GET 參數過去
<?php
$url = "http://example.com/";
$data_array = array("acc"=>"F", "pwd"=>"123");
$url = $url . http_build_query($data_array);
// 組出 http://sample.com/?acc=F&pwd=123
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
echo $output; // 把網頁內容印出來
如果是打 POST 過去
<?php
$url = "http://example.com/";
$data_array = array("username"=>"Falcon", "password"=>"123456");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
curl_close($ch);
echo $output; // 把網頁內容印出來
來看簡訊王的 API 文件
https://www.kotsms.com.tw/index.php?selectpage=pagenews&kind=4&viewnum=238
看起來很簡單只要有網址打 GET 參數過去,就成功發送囉!還可以直接用網頁來測試,那直接來看物件設計吧:
<?php
/**
* 串接簡訊王 API 用來發送簡訊
* https://www.kotsms.com.tw/
*/
class SMS {
private $content;
private $phoneNumber;
private $username;
private $password;
private $responseUrl = ''; // optional
function __construct($username, $password){
$this->username = $username;
$this->password = base64_decode($password);
}
function setContent($content){
$this->content = $content;
}
function setPhoneNumber($phoneNumber){
$this->phoneNumber = $phoneNumber;
}
function setResponseUrl($responseUrl){
$this->responseUrl = $responseUrl;
}
function send(){
if ( $this->content=='' || !preg_match('/^09([0-9]{8})$/', $this->phoneNumber) || $this->username=='' || $this->password=='' ){
return 'ERROR Params.';
}
$data = array(
'username' =>$this->username,
'apikey' =>$this->password,
'dstaddr' =>$this->phoneNumber,
'response' =>$this->responseUrl,
'smbody' =>iconv("UTF-8","big5//TRANSLIT",$this->content));
$querystring = http_build_query($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.kotsms.com.tw/kotsmsapi-1.php?".$querystring);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
$this->phoneNumber = '';
$this->content = '';
return $result;
}
}
記得 composer dump 把 SMS 加入函式庫
使用上也不難 在 Config 開好參數 SMS_USERNAME 與 SMS_PASSWORD
填好 $content 與目標 $phoneNumber 電話號碼即可
$SMS = new SMS(Config::SMS_USERNAME, Config::SMS_PASSWORD);
$SMS->setContent($content);
$SMS->setPhoneNumber($phoneNumber);
$SMS->send();